package com.tp2.etna.distribucion2.dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;

import javax.sql.DataSource;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import com.tp2.etna.distribucion2.modelo.BackOrder;
import com.tp2.etna.distribucion2.modelo.ProductoBackOrder;

@Repository
public class ProductoBackOrderDAOImpl implements ProductoBackOrderDAO {

	@Autowired
    private DataSource dataSource;
	
	@Override
	public boolean insertar(BackOrder backOrder) {
		String query = "insert into ProductoBackOrder (idProducto,idBackorder,cantidad) values(?,?,?)";
		Connection con = null;
		PreparedStatement ps = null;
		for (ProductoBackOrder detalle : backOrder.getDetalle()) {
			try{
		        con = dataSource.getConnection();
		        ps = con.prepareStatement(query);
		        ps.setInt(1, detalle.getProducto().getCodigo());
		        ps.setInt(2, backOrder.getCodigo());
		        ps.setInt(3, detalle.getCantidad());
		       
		        int result = ps.executeUpdate();
		        
		        if(result == 0)
		        return false;
		    }catch(SQLException e){
		        e.printStackTrace();
		    }finally{
		        try {
		            ps.close();
		            con.close();
		        } catch (SQLException e) {
		            e.printStackTrace();
		        }
		    }
		}
		
		return true;
	}

}
